
/**
 * parentTableSelector: 父table的css selector名称例如.class、#id。用于document.querySelector
 * expandTable: 包裹扩展表的el-table-column 或者 包裹扩展表的div 节点元素 或者 包裹扩展表el-table 元素
 */
function watchParantTable({ expandTable, parentTableSelector }: {expandTable: HTMLElment; parentTableSelector: string}) {
  try {
    const parentEl = document.querySelector(parentTableSelector)
    const scrollContainer = document.querySelector(`${parentTableSelector} .el-scrollbar__wrap`)
  
    // 初始化时 直接展开
    if (parentEl && scrollContainer) {
      expandTable.style.setProperty("width", parentEl.getBoundingClientRect().width + scrollContainer.scrollLeft + 'px')
    } else {
      console.warn("expandtable directive => Element not found(1)")
    }
  
    // 监听尺寸变化
    const resizeObserver = new ResizeObserver((entries) => {
      const targetEntry = entries[0]
      if (!targetEntry) {
        console.warn("expandtable directive => target entry not found")
        return
      }

      if (parentEl && scrollContainer) {
        expandTable.style.setProperty("width", parentEl.getBoundingClientRect().width + scrollContainer.scrollLeft + 'px')
      } else {
        console.warn("expandtable directive => Element not found(2)")
      }
    })
  
    if (parentEl) {
      resizeObserver.observe(parentEl)
    } else {
      console.warn("expandtable directive => parentTable Element not found")
    }
  
    // 监听父table滚动条滚动
    if (scrollContainer) {
      scrollContainer.addEventListener("scroll", resizeForParentScrollChange.bind(this, scrollContainer, parentEl, expandTable))
    } else {
      console.warn("expandtable directive => scrollContainer not found")
    }
  
    return {
      resizeObserver,
      parentEl,
      expandTable,
      scrollContainer,
    }
  } catch (e) {
    console.warn("监听扩展表格宽度失败：")
    console.warn(e)
  }
}

function resizeForParentScrollChange(scrollContainer, parentEl, expandTable) {
  expandTable.style.setProperty("width", parentEl.getBoundingClientRect().width + scrollContainer.scrollLeft + 'px')
}


/**
 * el-table 中有column type为expand 且 内嵌了一个子el-table时，子el-table的宽度不能确定
 * 通过此指令监听父table宽度，设置子table宽度
 */
export const expandTableAutoResize = {
  resizeObserver: null,
  scrollContainer: null,

  mounted(el: HTMLElement, binding: { value: {parentTableSelector: string}}) {
    const { resizeObserver, scrollContainer } = watchParantTable({
      expandTable: el, 
      parentTableSelector: binding?.value?.parentTableSelector 
    })

    expandTableAutoResize.resizeObserver = resizeObserver
    expandTableAutoResize.scrollContainer = scrollContainer
  },

  beforeUnmount() {
    expandTableAutoResize.resizeObserver.disconnect()
    expandTableAutoResize.scrollContainer.removeEventListener("scroll", resizeForParentScrollChange)
  },
}